package com.niit.session19;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
	public static void main(String[] args) {
		StudentDao studentDao = new StudentDao();
//		try {
////			boolean addStudent = studentDao.addStudent(new Student("1", "Trout", "男", 1, 2));
////			if(addStudent) {
////				System.out.println("添加成功！");
////			}
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
		List<Student> listStudent = studentDao.listStudent();
		for (Student student : listStudent) {
			System.out.println(student);
			
		}
	}
	/**
	 * 添加学生
	 * @param student
	 * @return
	 * @throws SQLException
	 */
	public boolean addStudent(Student student) throws SQLException {
		Connection conn = JDBCUtils.getConn();
		Statement statement = conn.createStatement();
		String sql = "insert into student value('" + student.getSid() + "','" + student.getName() + "','"
				+ student.getGender() + "'," + student.getBatch() + "," + student.getGroupLeader() + ")";
		System.out.println(sql);
//		executeUpdate的返回值是int类型的受影响的行数
		int update = statement.executeUpdate(sql);
		JDBCUtils.close(conn, statement, null);
		return update > 0 ? true : false;
	}
	/**
	 * 查询1班的学生
	 * @return
	 */
	public List<Student> listStudent(){
		List<Student> list = new ArrayList<Student>();
		Connection conn = null;
		Statement statement =  null;
		ResultSet rs =  null;
		try {
			conn = JDBCUtils.getConn();
			statement = conn.createStatement();
			rs = statement.executeQuery("select * from student where batch = 1");
			while (rs.next()) {
				list.add(new Student(rs.getString("sid"),rs.getString("name"),rs.getString("gender"),rs.getInt("batch"),rs.getInt("group_leader")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.close(conn, statement, rs);
		}
		return list;
		
	}
}
